package com.quanyan.club.task.tracker;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.api.APIResponse;
import com.quanyan.club.entity.db.TbClubIntegralRule;
import com.quanyan.club.entity.db.TbClubIntegralRuleExample;
import com.quanyan.club.entity.vo.resp.movement.ClubIntegralInfo;
import com.quanyan.club.mapper.*;
import com.quanyan.comment.reqeust.ReqBaseParam;
import com.quanyan.comment.response.RespCommentSum;
import com.quanyan.comment.serviceFacade.CommentServiceFacade;
import com.quanyan.common.constants.Constants;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;

/**
 * create by xian-guo
 * 同步俱乐部积分，只同步一次
 */
@Component
public class ClubIntegralTaskJob implements JobRunner{

    private static Logger logger = Logger.getLogger(ClubIntegralTaskJob.class);

    @Autowired
    private ClubIntegralMapper clubIntegralMapper;
    @Autowired
    private TbClubIntegralRuleMapper tbClubIntegralRuleMapper;
    @Autowired
    private CommentServiceFacade commentServiceFacade;//评论系统

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        try {
            TbClubIntegralRuleExample tbClubIntegralRuleExampleContro=new TbClubIntegralRuleExample();
            tbClubIntegralRuleExampleContro.createCriteria().andTypeEqualTo((byte) 0).andIsDeleteEqualTo((byte) 0);
            List<TbClubIntegralRule> tbClubIntegralRuleListC=tbClubIntegralRuleMapper.selectByExample(tbClubIntegralRuleExampleContro);
            if (CollectionUtils.isEmpty(tbClubIntegralRuleListC)){//只允许同步一次，标示统一同步俱乐部积分已经结束，以后都无需再同步
                logger.warn("----------------------无需同步俱乐部积分，已同步过了--------------------------------");
                return new Result(Action.EXECUTE_SUCCESS);
            }
            logger.warn("------------------俱乐部积分同步统计任务开始了-----------------------------");
            //统计俱乐部评分星级和人数
            ReqBaseParam reqBaseParam=new ReqBaseParam();
            reqBaseParam.setSystemCode(Constants.CLUB_SYSTEM_CODE);
            reqBaseParam.setBusinessCode(Constants.CLUB_ACTIVITY_COMMENT_BUSINESS_CODE);
            APIResponse<List<RespCommentSum>> apiResponse=commentServiceFacade.batchQueryClubCommentSum(reqBaseParam);
            logger.warn("----用户中心全部俱乐部星级信息---->>>>"+JSON.toJSONString(apiResponse));
            if (!apiResponse.isRet()) {
                return new Result(Action.EXECUTE_LATER);
            }
            List<RespCommentSum> respCommentList=apiResponse.getData();
            if (CollectionUtils.isEmpty(respCommentList)){
                return new Result(Action.EXECUTE_LATER);
            }
            DecimalFormat dfor=new DecimalFormat("#.00");
            dfor.setRoundingMode(RoundingMode.HALF_UP);
            List<ClubIntegralInfo> clubIntegralInfoList= clubIntegralMapper.getClubMember(null);//获取俱乐部人数
            for (RespCommentSum respCommentSum:respCommentList){
                for (ClubIntegralInfo clubIntegral:clubIntegralInfoList){
                    if (clubIntegral.getClubId().equals(respCommentSum.getBusinessId())){//对应俱乐部设置星级
                        clubIntegral.setClubStar(Double.valueOf(dfor.format(respCommentSum.getTotalScore())));//总星级
                        int comCount=respCommentSum.getClubCommentCount()!=null?respCommentSum.getClubCommentCount():0;//俱乐部活动评价数
                        clubIntegral.setActivityNum(comCount);
                        break;
                    }
                }
            }
            //积分规则
            TbClubIntegralRuleExample tbClubIntegralRuleExample=new TbClubIntegralRuleExample();
            tbClubIntegralRuleExample.createCriteria().andIsDeleteEqualTo((byte) 0);
            List<TbClubIntegralRule> tbClubIntegralRuleList=tbClubIntegralRuleMapper.selectByExample(tbClubIntegralRuleExample);
            //评分体系
            TbClubIntegralRule tbClubIntegralRule=tbClubIntegralRuleList.get(0);
            String[] strGrade=tbClubIntegralRule.getFinishGrade().split("-");//评分
            List<Double> gradeList=new ArrayList<>();
            for (int i=0;i<strGrade.length;i++){
                gradeList.add(Double.valueOf(strGrade[i]));
            }
            String[] strPoint=tbClubIntegralRule.getPoint().split("-");//对应的积分
            List<Double> pointList=new ArrayList<>();
            for (int i=0;i<strPoint.length;i++){
                pointList.add(Double.valueOf(strPoint[i]));
            }
            //俱乐部成员
            TbClubIntegralRule tbClubIntegralRuleM=tbClubIntegralRuleList.get(1);
            String[] strGradeM=tbClubIntegralRuleM.getFinishGrade().split("-");//评分
            List<Integer> gradeListM=new ArrayList<>();
            for (int i=0;i<strGradeM.length;i++){
                gradeListM.add(Integer.valueOf(strGradeM[i]));
            }
            String[] strPointM=tbClubIntegralRuleM.getPoint().split("-");//对应的积分
            List<Double> pointListM=new ArrayList<>();
            for (int i=0;i<strPointM.length;i++){
                pointListM.add(Double.valueOf(strPointM[i]));
            }
            DecimalFormat df=new DecimalFormat("#.0");
            df.setRoundingMode(RoundingMode.HALF_UP);
            for (ClubIntegralInfo clubIntegralInfo:clubIntegralInfoList){
                int activityNum=clubIntegralInfo.getActivityNum();//总评论数
                double clubStar=0.00;
                if (activityNum>0){
                    clubStar=Double.valueOf(dfor.format(clubIntegralInfo.getClubStar()/activityNum));//计算星级评分
                }
                for (int i=0;i<gradeList.size();i++){
                    if (clubStar>=gradeList.get(gradeList.size()-1)){//最后一个范围
                        clubIntegralInfo.setIntegeral(Math.round(Double.valueOf(df.format((pointList.get(pointList.size()-1) * (1+tbClubIntegralRule.getRate())) * 10))));
                        break;
                    }
                    if (clubStar<=gradeList.get(i)){
                        clubIntegralInfo.setIntegeral(Math.round(Double.valueOf(df.format((pointList.get(i) * (1+tbClubIntegralRule.getRate())) * 10))));
                        break;
                    }
                }
                int memberNum=clubIntegralInfo.getMemberNum();//计算俱乐部成员
                for (int i=0;i<gradeListM.size();i++){
                    if(memberNum>gradeListM.get(gradeListM.size()-1)){
                        clubIntegralInfo.setIntegeral(clubIntegralInfo.getIntegeral()+Math.round(Double.valueOf(df.format(pointListM.get(pointListM.size()-1) * (1+tbClubIntegralRuleM.getRate()) * 10))));
                        break;
                    }
                    if (memberNum<gradeListM.get(0)){//<1  =0分
                        clubIntegralInfo.setIntegeral(clubIntegralInfo.getIntegeral()+Math.round(Double.valueOf(df.format(pointListM.get(0) * (1+tbClubIntegralRuleM.getRate()) * 10))));
                        break;
                    }
                    if (memberNum==gradeListM.get(0)){//=1 =0.5分
                        clubIntegralInfo.setIntegeral(clubIntegralInfo.getIntegeral()+Math.round(Double.valueOf(df.format(pointListM.get(1) * (1+tbClubIntegralRuleM.getRate()) * 10))));
                        break;
                    }
                    if (memberNum<=gradeListM.get(i)){
                        clubIntegralInfo.setIntegeral(clubIntegralInfo.getIntegeral()+Math.round(Double.valueOf(df.format(pointListM.get(i) * (1+tbClubIntegralRuleM.getRate()) * 10))));
                        break;
                    }
                }
            }
            logger.debug("------------积分统计任务数据------------------------"+JSON.toJSONString(clubIntegralInfoList));
            int upCount= clubIntegralMapper.batchUpdateClubIntegral(clubIntegralInfoList);//批量跟新俱乐部积分
            if (upCount>0){
                logger.warn("------------积分统计任务数据完成------------------------");
                TbClubIntegralRule rules=tbClubIntegralRuleListC.get(0);
                rules.setIsDelete((byte) 1);
                tbClubIntegralRuleMapper.updateByExampleSelective(rules,tbClubIntegralRuleExampleContro);//跟新状态，后续不允许同步
                return new Result(Action.EXECUTE_SUCCESS);
            }
        }catch (Exception e){
            logger.warn("----"+e.getMessage());
            return new Result(Action.EXECUTE_LATER);
        }
        return new Result(Action.EXECUTE_LATER);
    }
}
